<script setup>
import { ref, onMounted } from 'vue'
import { Search, Folder, Document, Back, HomeFilled, ArrowRightBold, RefreshRight } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

//定义变量-------------------------------------------------

let searchkey = ref('') //搜索关键字
let fullscreenLoading = ref(false) //加载动画
let searchresult = ref([]) //搜索结果
let issearch = ref(false) //是否搜索
let resulttitle = ref('') //搜索结果标题
let resultdetail = ref('') //搜索结果详情
let drawer2 = ref(false) //文件内容弹窗
let path = ref([]) //定义初始导航栏路径
let lawdata = ref({  //定义初始化的法律数据
  showtxt: false,
  lawtxt: "",
  alllaw: [],
  currentlaw: []
})


//函数定义定义-------------------------------------------------------

onMounted(() => {
  //先读取本地存储
  let readdata = JSON.parse(localStorage.getItem('lawdata'))
  console.log('local', readdata)
  if (readdata != null) {
    //vue自动显示数据
    lawdata.value.alllaw = readdata
    lawdata.value.currentlaw = readdata
    return
  }

  //如果读本地失败，读取远程数据

  fullscreenLoading.value = true //显示加载动画

  //获取法律数据
  axios.get('../law.json').then(res => {
    console.log('remote', res.data)
    //写入本地存储
    localStorage.setItem('lawdata', JSON.stringify(res.data))
    //vue自动显示数据
    lawdata.value.alllaw = res.data
    lawdata.value.currentlaw = res.data
    fullscreenLoading.value = false //隐藏加载动画
  }).catch(err => {
    console.log(err)
    ElMessage({
      message: '加载失败.',
      type: 'warning',
    })
    fullscreenLoading.value = false //隐藏加载动画
  })
})

//清理缓存，刷新页面
function reload() {
  localStorage.removeItem('lawdata')
  location.reload()
}


//弹窗显示法律文件内容，关键字高亮显示
function showfile(e, path) {
  let cl = lawdata.value.alllaw
  let pathary = path.split('/')
  for (let i = 0; i < pathary.length - 1; i++) {
    cl = cl[pathary[i]]
  }

  //显示文件标题
  resulttitle.value = pathary[pathary.length - 2].replace(".txt", '')

  //高亮搜索关键字
  resultdetail.value = cl.replaceAll(searchkey.value, '<font color=\'red\'>' + searchkey.value + '</font>')

  //弹窗显示
  drawer2.value = true

}

//返回上一级
function goback() {
  //清除搜索状态
  issearch.value = false
  searchkey.value = ""

  path.value.pop() //删除最后一个路径元素
  lawdata.value.showtxt = false //不显示法律内容
  lawdata.value.lawtxt = ""

  //如果路径为空，显示所有法律（根目录）
  if (path.value.length == 0) {
    lawdata.value.currentlaw = lawdata.value.alllaw
    return
  }

  //根据路径数组，显示当前目录下的法律
  let templaw = lawdata.value.alllaw
  for (let i = 0; i < path.value.length; i++) {
    templaw = templaw[path.value[i]]
  }
  lawdata.value.currentlaw = templaw


}

//返回根目录
function gohome() {
  path.value = []
  lawdata.value.showtxt = false
  lawdata.value.lawtxt = ""
  lawdata.value.currentlaw = lawdata.value.alllaw
  issearch.value = false
  searchkey.value = ""
}

//打开目录，显示目录列表或者法律内容
function opendir(e, index) {
  path.value.push(index) //添加路径元素到栈
  if (index.indexOf('txt') > 0) {
    //如果是txt文件，显示法律内容
    lawdata.value.showtxt = true
    lawdata.value.lawtxt = lawdata.value.currentlaw[index]
    return
  } else {
    //如果是目录，显示目录下的法律列表和目录列表
    lawdata.value.showtxt = false
    lawdata.value.lawtxt = ""
    lawdata.value.currentlaw = lawdata.value.currentlaw[index]
  }
}

//搜索栏搜索响应handler
function search() {
  let searchtxt = searchkey.value
  if (searchtxt == "") {
    return
  }
  //搜索法律内容前先将所有变量初始化
  lawdata.value.showtxt = false
  lawdata.value.lawtxt = ""
  lawdata.value.currentlaw = lawdata.value.alllaw
  path.value = []
  searchresult.value = [] //搜索结果清空

  //搜索法律内容  
  searchlaw(lawdata.value.alllaw, "")
  issearch.value = true
}

/*
*递归遍历lawdata.value.alllaw,搜索关键字
*/
function searchlaw(lawdata, path) {
  for (let key in lawdata) {
    let pathvar = path + key + '/' //当前搜索路径
    if (key.indexOf('.txt') > 0) {  //如果是txt文件就进行内容搜索
      let res = "" //结果字符串初始化

      // 构造正则表达式
      var regex = new RegExp("<p>[^<]*" + searchkey.value + "[^<]*<\/p>", "ig");
      // 在html中查找所有匹配的内容
      var matches = lawdata[key].match(regex);
      if (matches) {
        // 定义一个数组来保存所有匹配的结果
        var nhtary = [];
        // 遍历每个匹配结果，保存到nhtary中
        for (var i = 0; i < matches.length; i++) {
          nhtary.push(matches[i]);
        }
        //拼合数组nhtary        
        for (let i = 0; i < nhtary.length; i++) {
          res += nhtary[i].replace(searchkey.value, '<font color=\'red\'>' + searchkey.value + '</font>') + '...'
        }
        //searchresult.value.push({ 'lawname': key, 'lawcontent': res, path: pathvar })
      }

      if (lawdata[key].indexOf(searchkey.value) > 0) { //这个判定条件似乎多此一举，因为上面已经有了正则表达式的判定
        searchresult.value.push({ 'lawname': key, 'lawcontent': res, path: pathvar })
      }
    } else {
      searchlaw(lawdata[key], pathvar) //递归搜索目录
    }
  }
}
</script>

<template>
  <div class="placeholds"></div>
  <main v-loading.fullscreen.lock="fullscreenLoading" class="content">
    <div class="fixed">
      <div class="fixedconent">
        <!--头部-->
        <el-page-header @back="goback">
          <template #breadcrumb>
            <el-breadcrumb separator="|" :to="{ path: '/' }">
              <el-breadcrumb-item>                
                  <el-icon size="15" color="#999900"  @click="gohome">
                    <HomeFilled />
                  </el-icon>                 
              </el-breadcrumb-item>
              <el-breadcrumb-item v-for="(item, index) in path">
                {{ item.replace(".txt", '') }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </template>
          <template #content>
            <span class="text-large font-600 mr-3"> 文化执法法律法规汇编 </span>
          </template>
        </el-page-header>
        <!--头部end-->


        <!--搜索框-->
        <div class="mt-4">
          <el-input v-model="searchkey" size="large" placeholder="输入关键字搜索" class="input-with-select"
            @keyup.enter.native="search">
            <template #prepend>
              <el-icon @click="gohome" size="20">
                <HomeFilled />
              </el-icon>　
              <el-icon @click="reload" size="20">
                <RefreshRight />
              </el-icon>
            </template>
            <template #append>
              <el-button :icon="Search" @click="search" />
            </template>
          </el-input>
        </div>
        <!--搜索框END-->
      </div>
    </div>

    <!--搜索结果LIST-->
    <div class="mt-4" v-if="issearch">
      <div v-for="(item, index) in searchresult" @click="showfile($event, item.path)">
        <div class="stitle">{{ item.lawname.replace(".txt", '') }}</div>
        <div class="scontent" v-html="item.lawcontent"> </div>
        <div class="spath"> {{ item.path.replace('.txt', '') }}</div>
      </div>
    </div>

    <template v-if="!issearch">
      <!--法律内容-->
      <div class="mt-4 lawcontent" v-if="lawdata.showtxt">
        <div v-html="lawdata.lawtxt" id="lawtxt"></div>
        <el-backtop :right="100" :bottom="100" visibility-height="200" />
      </div>

      <!--法律列表-->
      <div class="mt-4" v-if="!lawdata.showtxt">
        <div class="lawlist" v-for="(item, index) in lawdata.currentlaw" @click="opendir($event, index)">
          <el-icon class="icons" size="20" color="#999900" v-if="index.indexOf('txt') < 0">
            <Folder />
          </el-icon>
          <el-icon class="icons" size="20" color="#999900" v-if="index.indexOf('txt') > 0">
            <Document />
          </el-icon>
          <div class="lawtitle"> {{ index.replace(".txt", '') }}</div>
        </div>
      </div>
    </template>

  </main>
  <!--搜索文件内容弹窗显示-->
  <el-drawer v-model="drawer2" direction="btt" size="80%">
    <template #header>
      <h2>【{{ resulttitle }}】 </h2>
    </template>
    <template #default>
      <div v-html="resultdetail"></div>
    </template>
    <template #footer>
      <div style="flex: auto">
      </div>
    </template>
  </el-drawer>
</template>
<style  >
.path {
  color: #999900;
  border-radius: 5px;
  padding: 2px 10px;
  border: 1px solid #999900;
}

.mt-4 {
  margin-top: 5px;
}

#lawtxt p {
  margin-top: 10px;
}

.stitle {
  font-size: 20px;
  font-weight: bold;
}

.scontent {
  font-size: 16px;
}

.spath {
  font-size: 12px;
  color: #999900;
  border-bottom: 1px dashed #999;
  margin: 10px 0px;
  padding-bottom: 10px;
}

.lawlist {
  display: flex;
  align-items: center;
  border-bottom: 1px dashed #999;
  margin-top: 10px;
}

.lawtitle {
  display: inline-block;
  margin-left: 10px;
}

.fixed {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: white;
}

.fixedconent {
  margin: 0 auto;
  height: 150px;
  width: 100%;
  max-width: 1280px;
  padding: 32px 32px 0;
}

.placeholds {
  height: 120px;
}
</style>